﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharpSoda.Message
{
    public class MessageSessionGroup
    {
        private Dictionary<string, IMessageSession> m_Sessions = new Dictionary<string, IMessageSession>();

        public bool AddSession(IMessageSession session, string specifiedId = null)
        {
            if (session == null) return false;
            
            bool result = false;
            string sessionId = specifiedId;
            if (sessionId == null) sessionId = session.GetId();
            lock (m_Sessions)
            {
                if (!m_Sessions.ContainsKey(sessionId))
                {
                    m_Sessions.Add(sessionId, session);
                    result = true;
                }
            }
            return result;
        }

        public IMessageSession GetSession(string sessionId)
        {
            IMessageSession result = null;
            lock (m_Sessions)
            {
                if (m_Sessions.ContainsKey(sessionId))
                {
                    result = m_Sessions[sessionId];
                }
            }
            return result;
        }

        public List<IMessageSession> GetSessionList()
        {
            List<IMessageSession> result = new List<IMessageSession>();
            lock (m_Sessions)
            {
                foreach(var item in m_Sessions)
                {
                    result.Add(item.Value);
                }
            }
            return result;
        }

        public Dictionary<string, IMessageSession> GetSessionMap()
        {
            return m_Sessions;
        }

        public void RemoveSession(string sessionId)
        {
            lock (m_Sessions)
            {
                if (m_Sessions.ContainsKey(sessionId))
                {
                    m_Sessions.Remove(sessionId);
                }
            }
        }

        public void Broadcast(string data)
        {
            List<IMessageSession> sessions = GetSessionList();
            foreach(IMessageSession session in sessions)
            {
                session.Send(data);
            }
        }
    }
}
